package com.starinside.wp.controller.api;

import com.starinside.wp.domain.WxUser;
import com.starinside.wp.domain.familyTest.TestStoreObsTask;
import com.starinside.wp.foundation.DO.ObsPointRecordItemDO;
import com.starinside.wp.foundation.exception.BusinessException;
import com.starinside.wp.foundation.model.ErrorCode;
import com.starinside.wp.foundation.model.StatusResponse;
import com.starinside.wp.foundation.query.base.PagerQuery;
import com.starinside.wp.foundation.vo.BindedBabyVO;
import com.starinside.wp.service.BindedBabyService;
import com.starinside.wp.service.ObsPointService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RequestMapping("/wx/api/observation")
@RestController
@Api(value ="/wx/api/observation", tags = "家长观测点相关")
public class APIFamilyObservationController {

    @Autowired
    ObsPointService obsPointService;

    @Autowired
    BindedBabyService bindedBabyService;

    @RequestMapping(value = "/getByStoreId", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取观测点数据", notes = "返回一个问题列表，以及选项")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "planId", value = "资料 id")
    })

    StatusResponse getByStoreId(Integer planId){
        List result = obsPointService.getObsPointByTestStoreId(planId);

        return StatusResponse.success(result);
    }

    @RequestMapping(value = "/allObsPointRecord", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取所有宝宝的观测点", notes = "返回一个观测记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "childrenId", value = "宝贝 id， 如果不特别指定，择返回当前用户所有宝宝的数据"),
            @ApiImplicitParam(name = "pageNum", value = "分页下标"),
            @ApiImplicitParam(name = "pageSize", value = "页容量")
    })
    StatusResponse allObsPointRecord(HttpServletRequest req, String childrenId, PagerQuery pagerQuery){
        String[] babyIds = null;

        if(StringUtils.isEmpty(childrenId)) {
            WxUser user = (WxUser) req.getSession().getAttribute("loginUser");

            List<BindedBabyVO> babies = bindedBabyService.getAllBindedBaby(user.getParentMobile());

            if (StringUtils.isEmpty(user.getParentId()) || StringUtils.isEmpty(user.getDefaultBabyId()) || StringUtils.isEmpty(user.getParentMobile())) {
                return StatusResponse.error(ErrorCode.CHILDREN_NOT_EXIST, "当前账号下没有宝宝信息");
            }

            babyIds = babies.stream().map(k -> {
                return k.getId();
            }).toArray(String[]::new);
        }else{
            babyIds = new String[]{childrenId};
        }

        Object result = obsPointService.getObsPointTaskByChildrenIds(babyIds, pagerQuery );

        return StatusResponse.success(result);
    }

    @RequestMapping(value = "/ObsPointRecord/{taskId}", method = RequestMethod.GET)
    @ResponseBody
    @ApiOperation(value = "获取观测记录详情", notes = "返回一个观测记录对象")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "taskId", value = "观测记录id"),
    })
    StatusResponse obsPointRecord(HttpServletRequest req, @PathVariable String taskId){
        TestStoreObsTask result = obsPointService.getObsPointTask(taskId);
        return StatusResponse.success(result);
    }

    @RequestMapping(value = "/saveObsPointRecord", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "保存观测点记录", notes = "返回一个问题列表，以及选项")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "childrenId", value = "宝贝 id"),
            @ApiImplicitParam(name = "planId", value = "资料 id"),
            @ApiImplicitParam(name = "item", value = "选项列表,题目id和选项id逗号分隔，可多个答案竖线分隔", example = "obsPointId,obsOptionId"),
    })
    StatusResponse saveObsPointRecord(HttpServletRequest req, String childrenId, Integer planId, String item){
        //先取此用户基本信息
        WxUser user = (WxUser) req.getSession().getAttribute("loginUser");

        if(StringUtils.isEmpty(user.getParentId()) || StringUtils.isEmpty(user.getDefaultBabyId()) || StringUtils.isEmpty(user.getParentMobile())){
            return StatusResponse.error(ErrorCode.CHILDREN_NOT_EXIST,"当前账号下没有宝宝信息");
        }

        String parentId = user.getParentId();
        BindedBabyVO bindedBaby = bindedBabyService.getBindedBaby(childrenId, user.getParentMobile());

        if(bindedBaby == null){
            throw new BusinessException("错误的宝宝id");
        }

        List<ObsPointRecordItemDO> items = new ArrayList<>();

        String[] ii = item.split("\\|");

        for(String s : ii){
            String[] values = s.split(",");
            if(values.length == 2){
                items.add(ObsPointRecordItemDO.of(Integer.parseInt(values[0]),Integer.parseInt(values[1])));
            }
        }

        TestStoreObsTask task = obsPointService.saveObsPointTask(parentId, childrenId, planId, items);

        return StatusResponse.success(task);
    }

}
